package com.qiche.controller.mgr;

import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.constant.AccountType;
import com.qiche.dto.AgentDto;
import com.qiche.dto.MerchantDto;
import com.qiche.model.*;
import com.qiche.service.AgentService;
import com.qiche.service.UserService;
import com.qiche.service.WorkstageService;
import com.qiche.util.PasswordHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代理商管理控制器
 * Created by Linzw on 2018/01/24.
 */
@Api(value = "/agents", description = "代理商管理控制器")
@RestController
@RequestMapping("/agents")
public class AgentController {

    @Autowired
    private AgentService agentService;

    @Autowired
    private UserService userService;

    @RequiresRoles("system:manager")
    @ApiOperation(value = "根据条件和分页获取门店列表")
    @GetMapping
    public Map<String, Object> getAll(Agent agent, @RequestParam(required = false, defaultValue = "1") int page,
                                      @RequestParam(required = false, defaultValue = "10") int limit) throws Exception {
        Map<String, Object> map = new HashMap<>();
        PageInfo<Agent> pageInfo = agentService.selectByPage(agent, page, limit);
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }


    @ApiOperation(value = "添加代理商")
    @Transactional
    @PostMapping
    public Result add(@RequestBody @Valid AgentDto agentDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.createByErrorMessage(bindingResult.getFieldError().getDefaultMessage());
        }
        User user = new User();
        user.setUsername(agentDto.getUsername());
        user.setPassword(agentDto.getPassword());
        user.setAccountType(AccountType.AGENT);
        Result saveUserResult = userService.saveUserBySystem(user);
        if (saveUserResult.isSuccess()) {
            Agent agent = new Agent();
            agent.setLandline(agentDto.getLandline());
            agent.setPhone(agentDto.getPhone());
            agent.setName(agentDto.getName());
            agent.setLinkman(agentDto.getLinkman());
            agent.setAccountId(((User) saveUserResult.getData()).getId());
            int saveCount = agentService.save(agent);
            if (saveCount > 0) {
                return Result.createBySuccessMessage("添加成功");
            }
        }
        return Result.createByErrorMessage("添加失败");
    }


    @ApiOperation(value = "编辑代理商")
    @Transactional
    @PutMapping
    public Result update(@RequestBody @Valid AgentDto agentDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.createByErrorMessage(bindingResult.getFieldError().getDefaultMessage());
        }
        if (StringUtils.isNotBlank(agentDto.getPassword())) {
            //认为是修改密码
            Agent agent = agentService.selectByKey(agentDto.getId());
            if (agent != null) {
                User user = userService.selectById(agent.getAccountId().longValue());
                if (user != null) {
                    user.setPassword(agentDto.getPassword());
                    PasswordHelper helper = new PasswordHelper();
                    helper.encryptPassword(user);
                    userService.updateNotNull(user);
                }
            }
        }
        Agent agent = new Agent();
        agent.setId(agentDto.getId());
        agent.setLandline(agentDto.getLandline());
        agent.setPhone(agentDto.getPhone());
        agent.setName(agentDto.getName());
        agent.setLinkman(agentDto.getLinkman());
        int updateCount = agentService.updateNotNull(agent);
        if (updateCount > 0) {
            return Result.createBySuccessMessage("更新成功");
        }
        return Result.createByErrorMessage("更新失败");
    }

    @ApiOperation(value = "根据ID删除代理商")
    @DeleteMapping(value = "/delete/{id}")
    @Transactional
    public Result delete(@PathVariable("id") Long agentId) {
        Agent agent = agentService.selectByKey(agentId);
        if (agent != null) {
            int deleteUserCount = userService.delete(agent.getAccountId());
            if (deleteUserCount > 0) {
                int deleteAgentCount = agentService.delete(agentId);
                if (deleteAgentCount > 0) {
                    return Result.createBySuccessMessage("删除成功");
                }
            }
        }
        return Result.createByErrorMessage("删除失败");
    }


    @ApiOperation(value = "根据ID获取代理商法信息")
    @GetMapping(value = "/getById/{id}")
    public Result getById(@PathVariable("id") Integer id) {
        Agent bean = agentService.selectByKey(id);
        if (bean == null) {
            return Result.createByErrorMessage("不存在的代理商");
        }
        User user = userService.selectById(bean.getAccountId().longValue());
        AgentDto dto = new AgentDto();
        dto.setLandline(bean.getLandline());
        dto.setLinkman(bean.getLinkman());
        dto.setPassword("");
        dto.setPhone(bean.getPhone());
        dto.setUsername(user.getUsername());
        dto.setName(bean.getName());
        return Result.createBySuccess(dto);
    }
}
